package com.mcflies.commons.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * CheckCodeImgTool.java
 * 
 * @describe：生成校验码图片工具类
 * @Copyright(c) 2012-2024 Study,mcfly
 * @author mcfly_jun
 */
public class CheckCodeImgTool {
	private static int CHECK_CODE_COUNT = 4;
	private static int CHECK_CODE_WIDTH = 62;
	private static int CHECK_CODE_HEIGHT = 22;
	private static int LINE = 4;
	private static String[] checkCodeArr = new String[]{"1","2","3","4","5","6","7","8","9","0"};
	
	/**
	 * 满足懒人的需要
	 * @return
	 */
	public static Map<String, BufferedImage> getSimpleImage(){
		return getBaseImage(-1, -1, null, -1,-1);
	}
	
	/**
	 * 所有验证码图片的基本方法
	 * @param width
	 * @param height
	 * @param font
	 * @param count
	 * @return
	 */
	public static Map<String, BufferedImage> getBaseImage(int width, int height, Font font,int count,int line) {
		Map<String, BufferedImage> imageMap = new HashMap<String, BufferedImage>();
		if(-1 == width){
			width = CHECK_CODE_WIDTH;
		}
		if(-1 == height){
			height = CHECK_CODE_HEIGHT;
		}
		if(-1 == count){
			count = CHECK_CODE_COUNT;
		}
		if(null == font){
			font  =  new Font("Courier New", 1, width/count);
		}
		if(-1 == line){
			line = LINE;
		}
		BufferedImage image = new BufferedImage(width,height,1);//创建一张图片
		Graphics grap = image.createGraphics();
		grap.setColor(getRandColor(200,250));
		grap.fillRect(0, 0, width, height);
		
		grap.setColor(getRandColor(160, 200));
		for (int i = 0; i < line; i++) {
			Random random = new Random();
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			grap.drawLine(x, y, x + xl, y + yl);
		}
		
		grap.setFont(font);
		StringBuilder sb = new StringBuilder();
		for(int i = 0 ; i < count ; i++){
			Random random = new Random();
			int index = random.nextInt(checkCodeArr.length);
			grap.setColor(new Color(20 + random.nextInt(110), 20 +  random.nextInt(110), 20 + random.nextInt(110)));
			int x = width / count * i;
		    int y = (height + font.getSize()) / 2 - 5;
		    grap.drawString(checkCodeArr[index], x, y);
		    sb.append(checkCodeArr[index]);
		}
		imageMap.put(sb.toString(), image);
		return imageMap;
	}
	
	 private static Color getRandColor(int from, int to) {
		    Random random = new Random();
		    if (to > 255)
		      from = 255;
		    if (to > 255)
		      to = 255;
		    int rang = Math.abs(to - from);
		    int r = from + random.nextInt(rang);
		    int g = from + random.nextInt(rang);
		    int b = from + random.nextInt(rang);
		    return new Color(r, g, b);
		  }
}
